package com.misc.tunewsreader;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class SectionListAdapter extends ArrayAdapter<ListItem> {

    private ArrayList<ListItem> items;
    private LayoutInflater vi;
    private boolean small_layout;

    public SectionListAdapter(Context context, ArrayList<ListItem> items) {
	super(context, 0, items);
	this.items = items;
	vi = (LayoutInflater) context
		.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	small_layout = false;
    }

    public void useSmallLayout(boolean use_small) {
	small_layout = use_small;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
	View view = convertView;

	final ListItem item = items.get(position);
	if (item != null) {
	    if (item.isSection()) {
		ListSection si = (ListSection) item;
		view = vi.inflate(R.layout.list_section, null);

		view.setOnClickListener(null);
		view.setOnLongClickListener(null);
		view.setLongClickable(false);

		final TextView sectionView = (TextView) view
			.findViewById(R.id.list_section_text);
		sectionView.setText(si.getTitle());
	    } else {
		ListEntry ei = (ListEntry) item;
		if (!small_layout) {
		    view = vi.inflate(R.layout.list_entry, null);
		} else {
		    view = vi.inflate(R.layout.list_entry_small, null);
		}
		final TextView title = (TextView) view
			.findViewById(R.id.list_item_title);

		final TextView full_name = (TextView) view
			.findViewById(R.id.list_item_full_text);

		final TextView counter = (TextView) view
			.findViewById(R.id.list_item_count);

		if (title != null) {
		    String text = ei.title;
		    if (ei.count > 0 && counter != null) {
			// text += " (" + ei.count + ")";
			counter.setText(" " + String.valueOf(ei.count) + " ");
			counter.setVisibility(View.VISIBLE);
		    } else if (ei.count == 0 && counter != null) {
			counter.setVisibility(View.INVISIBLE);
		    }
		    title.setText(text);
		}
		if (full_name != null)
		    full_name.setText(ei.full_name);

	    }
	}
	return view;
    }

}
